from rest_framework import viewsets, mixins
from rest_framework import exceptions
from rest_framework.decorators import action

from datacenter.models import DataWarehouse, Entity
from datacenter.services import data_service, dataware_service
from connection.serializers import ConnectionSerializer
from connection.filters import ConnectionFilter
from connection.services import connection_service
from libs.simple_responses import api_success
from libs.utils import parse_page_params
from libs.enums import Permission
from libs.decorators import required_query_parameters, permission_required
from datacenter.serializers import DynamicModelSerializer


class DataViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    queryset = DataWarehouse.objects.all()
    serializer_class = ConnectionSerializer
    filterset_class = ConnectionFilter
    ordering_fields = ('id',)

    @permission_required([Permission.DATA_CENTER_VIEW.value])
    @required_query_parameters(['connection_id', 'entity_key'])
    def list(self, request, *args, **kwargs):
        connection_id = request.query_params.get('connection_id')
        entity_key = request.query_params.get('entity_key')
        connection = connection_service.get_connection_by_id(connection_id)
        if not connection:
            raise exceptions.ParseError({'error': '未发现资源'})
        certificate = connection_service.get_other_side_certificate(connection_id)
        if not certificate or not certificate.data:
            raise exceptions.ParseError({'error': '未建立互联关系'})

        entity = None
        for e in certificate.data.get('entities'):
            if entity_key == e.get('key'):
                entity = e
                break
        if not entity:
            raise exceptions.ParseError({'error': '未发现资源'})

        model = dataware_service.get_model(certificate, entity_key)
        DynamicModelSerializer.Meta.model = model
        queryset = model.objects.all()
        total = queryset.count()
        page = self.paginate_queryset(queryset)
        items = DynamicModelSerializer(page, many=True).data
        data = {
            'total': total,
            'items': items
        }
        return api_success(data=data)

    @permission_required([Permission.DATA_CENTER_VIEW.value])
    @action(methods=['get'], detail=False)
    @required_query_parameters(['entity_id'])
    def me(self, request, *args, **kwargs):
        entity_id = request.query_params.get('entity_id')
        entity = Entity.objects.filter(id=entity_id).first()
        if not entity:
            raise exceptions.ParseError({'error': '未发现资源'})
        page, page_size = parse_page_params(request)
        total, items = data_service.get_handler(entity)(entity, page=page, page_size=page_size)
        data = {
            'total': total,
            'items': items
        }
        return api_success(data=data)
